package com.wxxymaker.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: Soft
 * @Date: 2018/5/8 19:42
 * @Desc:
 */
public class FileUtil {
    private final static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 根据根目录和文件名创建文件，同时删除根目录下所有文件
     * @param folder   根目录
     * @param filename 文件名
     * @return 新建的文件
     */
    public static File createFile(String folder, String filename) {
        File file   = new File(folder, filename);
        File parent = file.getParentFile();
        if (parent.isDirectory()) {
            for (File f : parent.listFiles()) {
                if (f.delete()) {
                    log.info("删除文件成功--> {}", f.getAbsolutePath());
                }
            }
        }
        if (!file.exists()) {
            try {
                if (file.createNewFile()){
                    log.info("新建文件成功--> {}", file.getAbsolutePath());
                }
            } catch (IOException e) {
                log.error("新建文件失败--> {}", e);
            }
        }
        return file;
    }

    /**
     * 将给定文件的目录创建出来
     * @param file 文件对象
     */
    public static File createFolder(File file) {
        File parentFile = file.getParentFile();
        if (!parentFile.exists() && !parentFile.mkdirs()) {
            return null;
        }
        return file;
    }

    /**
     * 获取分值配置
     */
    public static Map<String, Double> getStandardProp() throws IOException {
        Properties ps = new Properties();
        ps.load(new FileInputStream(getPropsFile()));
        Double one = Double.valueOf(ps.getProperty("one", "40"));
        Double twe = Double.valueOf(ps.getProperty("twe", "60"));
        Double three = Double.valueOf(ps.getProperty("three", "80"));
        Double four = Double.valueOf(ps.getProperty("four", "100"));

        Map<String, Double> map = new HashMap<>();
        map.put("one", one);
        map.put("twe", twe);
        map.put("three", three);
        map.put("four", four);
        return map;
    }

    public static File getPropsFile() throws FileNotFoundException {
        return ResourceUtils.getFile("classpath:standard.properties");
    }
}
